package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("user")
public class SmsController {

    @Autowired
    private SmsService smsService;

    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);

    @PostMapping("login")
    public ResponseEntity<Object> sendCheckCode(@RequestBody Map<String, Object> param) {

        //创建错误信息对象
        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("发送短信验证码失败,弟弟!!");

        try {
            //获取前端传入的手机号码
            String phone = String.valueOf(param.get("phone"));
            //调用service方法,查看输入的验证码是否正确
            Map<String, Object> sendCheckCode = this.smsService.sendCheckCode(phone);
            //获取map中键code的值
            int code = ((Integer) sendCheckCode.get("code")).intValue();
            //若map中的code值为3,则验证码输入正确
            if (code == 3) {
                //返回正确ok
                return ResponseEntity.ok(null);
            } else if (code == 1) {
                //等于1 就是验证码还未失效
                resultBuilder.errCode("000001").errMessage(sendCheckCode.get("msg").toString());
            }
        } catch (Exception e) {
            LOGGER.error("发送短信验证码失败,弟弟!", e);
        }

        //默认返回失败
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());
    }
}
